package com.lezijie.note.web;

import com.lezijie.note.po.User;
import com.lezijie.note.service.UserService;
import com.lezijie.note.vo.ResultInfo;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    UserService userService=new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String actionName=req.getParameter("actionName");
        if("login".equals(actionName)){
            UserLogin(req,resp);
        }
    }

    private void UserLogin(HttpServletRequest req, HttpServletResponse resp) {
        String username=req.getParameter("username");
        String pwd=req.getParameter("pwd");
        ResultInfo<User> userResultInfo = userService.UserLogin(username, pwd);
        if(userResultInfo.getCode()==1){
            req.getSession().setAttribute("user",userResultInfo.getResult());
            String rem = req.getParameter("rem");
            if("1".equals(rem)){
                Cookie cookie=new Cookie("user",username+"-"+pwd);
                cookie.setMaxAge(3*26*60*60);
                resp.addCookie(cookie);

            }else{
                Cookie cookie=new Cookie("user",null);
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
            try {
                resp.setContentType("text/html;charset=utf-8");
                resp.sendRedirect("/index.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        return userResultInfo;
    }
}
